<template>
  <div :id="mapId" style="width: 100%; height: 100%"></div>
  <div v-if="type === 'full'" id="popup" class="ol-popup">
    <a id="popup-closer" href="#" class="ol-popup-closer"></a>
    <div id="popup-content"></div>
  </div>
  <!-- <ConfigDialog ref="configDialogRef" /> -->
</template>

<script lang="ts" setup>
import { Map, View, Feature } from "ol";
import Overlay from "ol/Overlay";
import WMTS from "ol/source/WMTS";
import WMTSTileGrid from "ol/tilegrid/WMTS";
import Heatmap from "ol/layer/Heatmap";
import GeoJSON from "ol/format/GeoJSON";
import { Point } from "ol/geom";
import { Style, Icon } from "ol/style";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { boundingExtent, Extent, getCenter } from "ol/extent";
import { get as getProjection, Projection, transform } from "ol/proj";
import { getTopLeft, getWidth } from "ol/extent";
import "ol/ol.css";
import XYZ from "ol/source/XYZ";
import TileLayer from "ol/layer/Tile";
const OLD_TIANDITU_KEY = "5ec3e996393521a1a9fb1681f13201ff";
const NEW_TIANDITU_KEY = "df6d59aea23e0f175e7f556d65501193"; //个人申请， 底图无路网显示
import {
  onMounted,
  defineExpose,
  defineProps,
  ref,
  defineEmits,
  watch,
  unref,
} from "vue";
import marker from "@/assets/images/Marker.png";
// import ConfigDialog from '@/views/deviceManager/deviceMonitor/ConfigDialog.vue'
import { getCompressorStatusText } from "@/enums/compressorStatus";
import MapAPI from "../../../mock/map.mock";
const props = defineProps({
  type: {
    type: String,
    default: "",
  },
  deviceList: {
    type: Array,
    default: () => {
      return [];
    },
  },
  mapId: {
    type: String,
    default: "map",
  },
});

const showPopup = ref(false);
const type = ref(props.type);
const deviceList = ref(props.deviceList);
const map = ref();
const showData = ref(false);
const viewData = ref({});
// const baseLayers = ref([] as any[]);
const vectorLayer: any = ref({} as any);
// const globSetting = useGlobSetting()
const selectedDevice: any = ref<{
  brandIcon?: string;
  brandModel?: string;
  brandModelName?: string;
  channelId?: string;
  channelName?: string;
  coordinate?: null | string;
  createTime?: string;
  deviceCode?: string;
  deviceName?: string;
  deviceStatus?: string;
  gbId?: null | string;
  gid?: string;
  address?: "";
  groupId?: string;
  groupName?: string;
  isWarning?: number;
}>({});
// let layer: TileLayer<TileWMS>;

const allDeviceList = ref<Array<any>>([]);

const address = ref("");
const findAddressByCoord = async (coordinate: any) => {
  const params = {
    postStr: {
      lon: coordinate[0],
      lat: coordinate[1],
      ver: 1,
    },
    type: "geocode",
    tk: OLD_TIANDITU_KEY,
  };
  //   const res = await MapAPI.getAddress(params)

  //   if (res && res.status === '0') {
  //     address.value = res.result.formatted_address
  //   }
};

const emit = defineEmits(["setPoint"]);
// 地图撒点
const getAllDeviceInfo = async () => {
  // todo
  const tenantCode = "1";
  // const res = await getDeviceList(tenantCode)
  const res = {
    data: [
      {
        gid: "1815630726142361600",
        createTime: "2024-07-23 06:11:13",
        createBy: 0,
        updateTime: null,
        updateBy: null,
        deviceName: "1111111111",
        brandModel: null,
        deviceCode: "22222222",
        deviceType: 1,
        tenantCode: "1",
        coordinate: null,
        address: null,
        iotChannelInfo: null,
        virt: 0,
        deviceSn: "1111",
        deviceStatus: "OFFLINE",
        nodeType: "DIRECT",
        groupInfo: 222,
        orgInfo: "1815571033344704512",
        productInfo: 1,
        measureUnit: "2",
        manufacturerInfo: "2022092114235412545",
        brand: null,
        serviceTime: "2024-07-25 12:00:00",
        managerPassportInfo: "1815566853603328000",
        remark: null,
        img: "",
        deviceDocument: "",
        operateStatus: "ENABLE",
        ip: null,
        collectStatus: null,
        collectToggleLocked: 0,
        lastConnectTime: null,
        lastDisconnectTime: null,
        online: false,
        cardNumber: null,
        channelNumber: null,
      },
      {
        gid: "1815624348443082752",
        createTime: "2024-07-23 05:45:52",
        createBy: 0,
        updateTime: null,
        updateBy: null,
        deviceName: "光照探测器",
        brandModel: null,
        deviceCode: "932000",
        deviceType: 1,
        tenantCode: "1",
        coordinate: null,
        address: null,
        iotChannelInfo: null,
        virt: 0,
        deviceSn: "SN202306060001",
        deviceStatus: "OFFLINE",
        nodeType: "DIRECT",
        groupInfo: "1622877527955472384",
        orgInfo: "1815566053447565312",
        productInfo: "1811335170641362944",
        measureUnit: "lux",
        manufacturerInfo: 3,
        brand: null,
        serviceTime: null,
        managerPassportInfo: "1815566853603328000",
        remark: null,
        img: "",
        deviceDocument: "",
        operateStatus: "ENABLE",
        ip: null,
        collectStatus: null,
        collectToggleLocked: 0,
        lastConnectTime: null,
        lastDisconnectTime: null,
        online: false,
        cardNumber: null,
        channelNumber: null,
      },
      {
        gid: "1815624248559927296",
        createTime: "2024-07-23 05:45:28",
        createBy: 0,
        updateTime: null,
        updateBy: null,
        deviceName: "55555555",
        brandModel: null,
        deviceCode: "55555555",
        deviceType: 1,
        tenantCode: "1",
        coordinate: null,
        address: null,
        iotChannelInfo: null,
        virt: 0,
        deviceSn: "55",
        deviceStatus: "OFFLINE",
        nodeType: "DIRECT",
        groupInfo: 222,
        orgInfo: "1815566053447565312",
        productInfo: "1811327467802066944",
        measureUnit: "555555",
        manufacturerInfo: 2,
        brand: "555555",
        serviceTime: "2024-07-18 12:00:00",
        managerPassportInfo: null,
        remark: null,
        img: "",
        deviceDocument: "",
        operateStatus: "ENABLE",
        ip: null,
        collectStatus: null,
        collectToggleLocked: 0,
        lastConnectTime: null,
        lastDisconnectTime: null,
        online: false,
        cardNumber: null,
        channelNumber: null,
      },
      {
        gid: "1815193874134466560",
        createTime: "2024-07-23 03:09:44",
        createBy: null,
        updateTime: null,
        updateBy: null,
        deviceName: "20231208012",
        brandModel: null,
        deviceCode: "222",
        deviceType: 3,
        tenantCode: "1",
        coordinate: "114.26915852905275,30.64053004673265",
        address: null,
        iotChannelInfo: null,
        virt: 0,
        deviceSn: "20231208012",
        deviceStatus: null,
        nodeType: "DIRECT",
        groupInfo: 1,
        orgInfo: 1,
        productInfo: "1811327467802066944",
        measureUnit: "1",
        manufacturerInfo: "2022092114235412545",
        brand: null,
        serviceTime: null,
        managerPassportInfo: null,
        remark: null,
        img: "ceb192bd-204d-434d-8ad8-b3e4ed974986.png",
        deviceDocument: null,
        operateStatus: "ENABLE",
        ip: "192.168.1.222",
        collectStatus: "collecting",
        collectToggleLocked: 0,
        lastConnectTime: "2024-07-22 01:15:17",
        lastDisconnectTime: null,
        online: false,
        cardNumber: null,
        channelNumber: null,
      },
      {
        gid: "1815558918978404352",
        createTime: "2024-07-23 01:25:52",
        createBy: 0,
        updateTime: null,
        updateBy: null,
        deviceName: "测试传感器",
        brandModel: null,
        deviceCode: "123123",
        deviceType: 1,
        tenantCode: "1",
        coordinate: "114.26915852905275,30.64053004673265",
        address: null,
        iotChannelInfo: null,
        virt: 0,
        deviceSn: "456123",
        deviceStatus: "OFFLINE",
        nodeType: "DIRECT",
        groupInfo: 1,
        orgInfo: 1,
        productInfo: 1,
        measureUnit: "12",
        manufacturerInfo: "2022092114235412545",
        brand: "大1",
        serviceTime: "2024-07-20 12:00:00",
        managerPassportInfo: "1815283566968307712",
        remark: null,
        img: "0c3bd582-c95b-4ed1-9e5d-366e5d90b0a7.png",
        deviceDocument: "",
        operateStatus: "ENABLE",
        ip: "192.168.1.222",
        collectStatus: "collecting",
        collectToggleLocked: 0,
        lastConnectTime: "2024-07-22 01:15:17",
        lastDisconnectTime: null,
        online: false,
        cardNumber: null,
        channelNumber: null,
      },
    ],
    resMsg: "操作成功",
    resCode: "00000",
  };
  if (res && res.resCode === "00000") {
    allDeviceList.value = res.data;
    const features: any = [];
    for (let i = 0; i < allDeviceList.value.length; i++) {
      const device = allDeviceList.value[i];
      const coordinate = device.coordinate;
      console.log("coordinate", coordinate);
      if (!coordinate) return;
      const coordStrs = coordinate?.split(",");
      const feature = {
        type: "Feature",
        properties: {},
        geometry: { type: "Point", coordinates: [coordStrs[0], coordStrs[1]] },
      };
      features.push(feature);
    }
    var heatData = {
      type: "FeatureCollection",
      features: features,
    };
    var vectorSource: any = new VectorSource({
      features: new GeoJSON().readFeatures(heatData, {
        dataProjection: "EPSG:4326",
        featureProjection: "EPSG:4326",
      }),
    });
    // Heatmap热力图
    var vector = new Heatmap({
      source: vectorSource,
      blur: 15,
      radius: 5,
    });
    console.log("vector", vector);
    map.value?.addLayer(vector);
  }
};

const changeDialog = (params: any) => {
  const { flag, mode } = params;
  if (mode === "view") {
    showData.value = flag;
  }
};

const addVectorLabel = (coordinate: any) => {
  // let that = this;
  if (!vectorLayer.value) return; // 图层对象为undefined,地图未加载成功。则后续渲染操作无需继续
  // 新建一个要素 uni.Feature
  const newFeature = new Feature({
    geometry: new Point(coordinate), // 几何信息
    //            name: '地址标注'  //名称属性
  });
  newFeature.setStyle(
    new Style({
      image: new Icon({
        anchor: [0.5, 30],
        opacity: 1.0,
        anchorOrigin: "top-right",
        anchorXUnits: "fraction",
        anchorYUnits: "pixels",
        offsetOrigin: "top-right",
        src: marker, // 图标的url
        // name: '地址标注', //名称属性
      }),
    })
  ); // 设置要素的样式
  console.log("vectorLayer", vectorLayer.value);
  vectorLayer.value?.getSource()?.clear(); // 清空图层
  vectorLayer.value?.getSource()?.addFeature(newFeature); // 图层添加要素
  emit("setPoint", { address: address.value, coordinate: coordinate });
};
let overlay: any = null;

const initPoint = (deviceList: any, isShowPop = true) => {
  if (!vectorLayer.value) return;
  vectorLayer.value?.getSource()?.clear();
  if (deviceList && deviceList.length === 0) return;

  const newFeatures: Array<Feature<Point>> = [];
  deviceList.forEach((item: any) => {
    if (item && item.coordinate) {
      const newFeature = new Feature({
        geometry: new Point(item.coordinate.split(",")),
      });
      newFeature.set("deviceId", item.gid);
      newFeature.setStyle(
        new Style({
          image: new Icon({
            anchor: [0.5, 10],
            opacity: 1.0,
            anchorOrigin: "top-right",
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            offsetOrigin: "top-right",
            src: marker, // 图标的url
            // name: '地址标注', //名称属性
          }),
        })
      );
      newFeatures.push(newFeature);

      // feature的鼠标移入移出事件
      map.value?.on("pointermove", (event) => {
        if (event.dragging) return; // 忽略拖动时的事件

        const pixel = map.value?.getEventPixel(event.originalEvent);
        const hit = map.value?.hasFeatureAtPixel(pixel);
        // console.log("pixel", pixel, "hit", hit);
        if (hit) {
          const feature = map.value?.forEachFeatureAtPixel(
            pixel,
            function (feature) {
              return feature;
            }
          );
          if (feature) {
            const content = document.getElementById("popup-content");
            if (content) {
              // 更新信息框内容
              content.innerHTML =
                content.innerHTML = `<div class="deviceName mb-1">
              <span class="title font-bold text-lg">${item?.modelSet}</span>
            </div>
            <div class="content-container">
              <div class="content mb-1">
                <span class="">设备名称: ${item?.compressorModeName} ${item?.unumber}</span>
              </div>
              <div class="content mb-1">
                <span class="">设备地址: ${item?.address}</span>
              </div>
              <div class="content mb-1">
                <span class="deivce-status">设备状态: ${getCompressorStatusText(
                  item?.status
                )}</span>
              </div>
            </div>`;
              // 设置信息框位置
              overlay.setPosition(feature.getGeometry().getCoordinates());
              // 显示信息框
              overlay.setPosition(feature.getGeometry().getCoordinates());
            }
          }
        } else {
          // 如果鼠标不在特征上，隐藏信息框
          overlay.setPosition(undefined);
        }
      });
    }
  });

  // 由于 `pointermove` 事件会在整个地图上触发，因此还需要在地图上添加一个监听器来清除悬停效果，当鼠标离开所有特征时：
  map.value?.on("pointermove", (event) => {
    const pixel = map.value?.getEventPixel(event.originalEvent);
    const hit = map.value?.hasFeatureAtPixel(pixel);
    if (!hit) {
      overlay.setPosition(undefined);
    }
  });

  vectorLayer.value.getSource().addFeatures(newFeatures);
  // 气泡信息框,默认显示第一个设备气泡框
  // if (isShowPop) {
  //   selectedDevice.value = deviceList[0];
  //   const coordinate = deviceList[0].coordinate;
  //   if (!coordinate) return;
  //   const coordStrs = coordinate.split(",");
  //   showPopup.value = true;

  //   const content = document.getElementById("popup-content");
  //   if (content) {
  //     const coords = [Number(coordStrs[0]), Number(coordStrs[1])];
  //     content.innerHTML = `<div class="deviceName mb-1">
  //           <span class="title font-bold text-lg">${
  //             selectedDevice.value.modelSet
  //           }</span>
  //         </div>
  //         <div class="content-container">
  //           <div class="content mb-1">
  //             <span class="">设备编码: ${selectedDevice.value.unumber}</span>
  //           </div>
  //           <div class="content mb-1">
  //             <span class="">设备地址: ${selectedDevice.value.address}</span>
  //           </div>
  //           <div class="content mb-1">
  //             <span class="">所属机型: ${
  //               selectedDevice.value.compressorModeName
  //             }</span>
  //           </div>
  //           <div class="content mb-1">
  //             <span class="">设备状态: ${getCompressorStatusText(
  //               selectedDevice.value.status
  //             )}</span>
  //           </div>
  //         </div>`;
  //     overlay.setPosition(coords);
  //   }
  // }
};

const clear = () => {
  vectorLayer.value.getSource().clear();
};
// 地图应用开发者用来配置和加载特定地图服务的重要信息,开发者将天地图的服务集成到自己的地图应用中
const getMapSettingList = async () => {
  //   const list = await MapAPI.findAllTileInfoInList({})
  //    return list
  return [];
};
const closePopup = () => {
  const closer = document.getElementById("popup-closer");
  if (closer) {
    overlay.setPosition(undefined);
    closer.blur();
    return false;
  }
};

const initMap = async () => {
  const container = document.getElementById("popup");
  const closer = document.getElementById("popup-closer");
  if (closer) {
    closer.onclick = function () {
      overlay.setPosition(undefined);
      closer.blur();
      return false;
    };
  }

  overlay = new Overlay({
    element: container as HTMLElement | undefined,
    autoPan: {
      animation: {
        duration: 250,
      },
    },
  });

  const mapSetting = await getMapSettingList();
  const defaultProjection = getProjection("EPSG:4326");
  const defaultProjectionExtent: Array<number> =
    defaultProjection?.getExtent() as Array<number>;
  const defaultSize = getWidth(defaultProjectionExtent) / 256;
  const defaultResolutions = new Array(19);
  const defaultMatrixIds = new Array(19);
  for (let z = 0; z < 19; ++z) {
    // generate resolutions and matrixIds arrays for this WMTS
    defaultResolutions[z] = defaultSize / Math.pow(2, z);
    defaultMatrixIds[z] = z;
  }
  const defaultLayers = [
    new TileLayer({
      opacity: 1.0,
      source: new WMTS({
        attributions: "",
        url: "http://t4.tianditu.gov.cn/vec_c/wmts?tk=5ec3e996393521a1a9fb1681f13201ff",
        layer: "vec",
        matrixSet: "c",
        format: "tiles",
        projection: defaultProjection as Projection,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(defaultProjectionExtent),
          resolutions: defaultResolutions,
          matrixIds: defaultMatrixIds,
        }),
        style: "default",
        wrapX: false,
      }),
    }),
    new TileLayer({
      source: new WMTS({
        url: "http://t0.tianditu.gov.cn/cva_c/wmts?tk=5ec3e996393521a1a9fb1681f13201ff",
        layer: "cva",
        matrixSet: "c",
        format: "tiles",
        projection: "EPSG:4326",
        // tileLoadFunction:function (image,src) {
        //     image.getImage().src = src+"&tk="+tdtConfig.token
        // },
        // projection: defaultProjection as Projection,
        tileGrid: new WMTSTileGrid({
          origin: getTopLeft(defaultProjectionExtent),
          resolutions: defaultResolutions,
          matrixIds: defaultMatrixIds,
        }),
        style: "default",
      }),
    }),

    // 带蓝色滤镜，不显示街道等
    //   new TileLayer({
    //     opacity: 1.0,
    //     source: new XYZ({
    //       attributions: "",
    //       url: "http://t4.tianditu.com/DataServer?T=vec_w&tk=537a02079de03e723242caa7ad06a7d8&x={x}&y={y}&l={z}",
    //       // layer: "vec",
    //       // matrixSet: "c",
    //       // format: "tiles",
    //       // projection: defaultProjection as Projection,
    //       // tileGrid: new WMTSTileGrid({
    //       //   origin: getTopLeft(defaultProjectionExtent),
    //       //   resolutions: defaultResolutions,
    //       //   matrixIds: defaultMatrixIds,
    //       // }),
    //       // style: "default",
    //       // wrapX: false,
    //       //给openlayes加上底图滤镜
    //       tileLoadFunction: function (imageTile: any, src: any) {
    //         const img = new Image();
    //         img.setAttribute("crossOrigin", "anonymous");
    //         img.onload = function () {
    //           const canvas = document.createElement("canvas");
    //           const w = img.width;
    //           const h = img.height;
    //           canvas.width = w;
    //           canvas.height = h;
    //           const context = canvas.getContext("2d") as any;
    //           context.filter =
    //             "grayscale(98%) invert(100%) sepia(20%) hue-rotate(180deg) saturate(1600%) brightness(80%) contrast(90%)";
    //           context.drawImage(img, 0, 0, w, h, 0, 0, w, h);
    //           imageTile.getImage().src = canvas.toDataURL("image/png");
    //         };
    //         img.src = src;
    //       },
    //     }),
    //   }),
  ];
  let layers = [];
  if (mapSetting.resCode === "00000") {
    const list = mapSetting.data;
    if (list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        const o = list[i];
        const options = JSON.parse(o.options);
        const projection = getProjection(options.projection);
        const projectionExtent: Array<number> =
          projection?.getExtent() as Array<number>;
        const size = getWidth(projectionExtent) / 256;
        const resolutions = new Array(19);
        const matrixIds = new Array(19);
        //地图显隐
        const lyview = o.tileStatus === "隐藏" ? false : true;
        for (let z = 0; z < 19; ++z) {
          // generate resolutions and matrixIds arrays for this WMTS
          resolutions[z] = size / Math.pow(2, z);
          matrixIds[z] = z;
        }

        const l = new TileLayer({
          opacity: 1.0,
          visible: lyview,
          source: new XYZ({
            attributions: "",
            url: o.tileService,
            layer: options.layers,
            matrixSet: options.matrixSet,
            format: options.format,
            projection: projection as Projection,
            tileGrid: new WMTSTileGrid({
              origin: getTopLeft(projectionExtent),
              resolutions: resolutions,
              matrixIds: matrixIds,
            }),
            style: options.style,
            wrapX: false,
          }),
        });
        layers.push(l);
      }
    } else {
      layers = defaultLayers;
    }
  } else {
    layers = defaultLayers;
  }
  map.value = new Map({
    target: props.mapId,
    view: new View({
      projection: "EPSG:4326",
      center: [114.27551, 30.62048], // 自己设置中心点，也可以不设置
      zoom: 13, // 根据自己情况设置，可以不设置
      // minZoom: 4, //根据自己情况设置，可以不设置

      constrainResolution: true,
      smoothResolutionConstraint: false,
    }),
    layers: layers,
    overlays: [overlay],
  });

  vectorLayer.value = new VectorLayer({
    zIndex: 1000,
    source: new VectorSource({}),
  });

  map.value.addLayer(vectorLayer.value);
  initPoint(deviceList.value);

  if (type.value === "editAble") {
    map.value.on("click", async (evt: any) => {
      await findAddressByCoord(evt.coordinate);
      addVectorLabel(evt.coordinate);
      // 监听自己添加的feature点击事件，做点什么
    });
  } else if (type.value === "full") {
    map.value.on("click", (evt: any) => {
      selectedDevice.value = {};
      map.value.forEachFeatureAtPixel(evt.pixel, (features: any) => {
        const id = features.get("deviceId");
        allDeviceList.value.forEach((item) => {
          if (item.gid === id) {
            selectedDevice.value = item;
            showPopup.value = true;
          }
        });
      });
      const content = document.getElementById("popup-content");
      if (content && selectedDevice.value.deviceCode) {
        const coords = evt.coordinate;
        content.innerHTML = `<div class="deviceName mb-1">
              <span class="title font-bold text-lg">${selectedDevice.value.deviceName}</span>
            </div>
            <div class="content-container">
              <div class="content mb-1">
                <span class="">设备编码: ${selectedDevice.value.deviceCode}</span>
              </div>
              <div class="content mb-1">
                <span class="">设备地址: ${selectedDevice.value.address}</span>
              </div>
              <div class="content mb-1">
                <span class="">所属型号: ${selectedDevice.value.brandModelName}</span>
              </div>
              <div class="content mb-1">
                <span class="">设备状态: ${selectedDevice.value.deviceStatus}</span>
              </div>
              <div class="content mb-1">
                <span class="">通讯通道: ${selectedDevice.value.channelName}</span>
              </div>
            </div>
            <div class="float-right">
              <button class="text-blue-400 cursor-pointer" onClick="checkDataInfo()">查看上报数据</button>
            </div>`;
        overlay.setPosition(coords);
      }
    });
  }
};
const visible = ref(false);
const showDetail = () => {
  visible.value = true;
};
(window as any).showDetail = showDetail;

const configDialogRef = ref();
// const dataInfo = ref('<<< 数据通道连接中~~~~')
const checkDataInfo = async () => {
  // unref(configDialogRef).open(selectedDevice.value)
  // const val = selectedDevice.value
  // console.log('我是选中数据', val)
  // const wsIsClose = ref(true)
  // const ws = new WebSocket(useGlobSetting().wsUrl as string | URL)
  // const client = Stomp.over(ws)
  // if (typeof WebSocket === 'undefined') {
  //   console.log('不支持websocket')
  // } else {
  //   const onConnect = () => {
  //     console.log('<<< 连接成功~~~~~~~')
  //     dataInfo.value = '<<< 数据通道连接成功~~~~~~~'
  //     wsIsClose.value = false
  //     client.subscribe(
  //       `/exchange/messageTopicExchange/*.up.${val.productId}.${val.gid}`,
  //       async (data: any) => {
  //         if (typeof data !== 'undefined') {
  //           dataInfo.value = data.body + '\n' + dataInfo.value
  //           // const textarea = document.getElementsByClassName('n-input__textarea-mirror')[0];
  //           // if (textarea) {
  //           //   textarea.scrollTop = textarea?.scrollHeight;
  //           // }
  //           const result: any = await findAbstractModelByDevice({
  //             deviceId: selectedDevice.value.gid
  //           })
  //           viewData.value = { models: result.data, device: val, dataInfo, dataBody: data.body }
  //         }
  //       }
  //     )
  //   }
  //   const onError = () => {
  //     wsIsClose.value = true
  //     console.log('error')
  //   }
  //   client.connect('admin', 'Cxj123', onConnect, onError, '/')
  //   console.log(`>>>连接上${useGlobSetting().wsUrl}`)
  // }
  // // le
  // showData.value = true
  // watch(showData, (n) => {
  //   if (!n) {
  //     client.disconnect(() => {
  //       console.log('>>>断开链接')
  //       dataInfo.value = '<<< 数据通道连接中~~~~'
  //     })
  //   }
  // })
};
(window as any).checkDataInfo = checkDataInfo;

const setCenter = (coordinate: any) => {
  map.value.getView().setCenter(coordinate);
  map.value.getView().setZoom(16);
};

onMounted(async () => {
  // 先初始化地图，地图撒点才能生效
  // await initMap();
  getAllDeviceInfo();
});

defineExpose({ initMap, initPoint, setCenter, clear, closePopup });
</script>

<style lang="scss">
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 12px 0 0 16px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 300px;
  height: 214px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 20px;
  right: 19px;
  color: #333333;
}

.ol-popup-closer:after {
  content: "✖";
}

#popup-content {
  display: flex;
  flex-direction: column;

  .deviceName {
    font-size: 14px;
    font-weight: 700;
  }

  .content-container {
    margin: 6px 0 0 0;

    .content {
      height: 22px;
      line-height: 22px;
      margin-bottom: 4px;

      span {
        font-family:
          PingFang SC-Medium,
          PingFang SC;
        width: 208px;
        font-size: 14px;
        color: #333333;
        overflow: hidden;
        /*超出部分隐藏*/
        text-overflow: ellipsis;
        /*超出部分省略号表示*/
        white-space: nowrap;
        /*强制单行显示*/
        display: inline-block;
        /*转换为行内块元素*/
      }
    }
  }

  .float-right {
    margin-left: auto;
    margin: 0 16px 10px auto;

    .text-blue-400 {
      font-family:
        PingFang SC-Medium,
        PingFang SC;
      width: 96px;
      height: 28px;
      background-color: #2ca8ff;
      color: #fff;
      font-size: 12px;
      border: none;
      border-radius: 4px 4px 4px 4px;
    }
  }
}
</style>
